<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of payment
 *
 * @author b4by
 */
class order extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_order');
	}

	public function payment() {
		$this->load->helper('form');
		$this->load->helper('date');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('fullname', 'lang:fullname', 'required|min_length[6]|max_length[100]');
		$this->form_validation->set_rules('mobile', 'lang:mobile', 'required|min_length[8]|max_length[20]');
		$this->form_validation->set_rules('email', 'lang:email', 'required|valid_email');
		$this->form_validation->set_rules('address', 'lang:address', 'required|min_length[10]');
		$this->form_validation->set_rules('captcha', 'lang:captcha', 'required|callback__check_capcha');
		$this->form_validation->set_rules('product_id', 'lang:product', 'required|callback__check_product');

		if ($this->form_is_valid()) {
			$data = request_filter(array('fullname', 'mobile', 'product_id', 'address', 'email'));
			$data['time'] = now();
			$order_id = $this->model_order->create($data);
			$cart = $this->session->userdata('cart');
			array_push($cart, $data['product_id']);
			$this->session->set_userdata('cart',$cart);
			echo json_encode(array(
				'state' => 'success',
				'message' => lang('order_successfully'),
				'order_url' => url_create('site', 'order', 'index', $order_id)
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'errors' => $this->data['errors'],
			));
		}
	}

	public function _check_product($id) {
		$this->load->helper('date');
		$this->load->model('model_product');

		$product = $this->model_product->get_info($id);
//		pr($product);die;
		if ($product !== FALSE) {
			if ($product->end >= now() && $product->active == 1) {
				$cart = $this->session->userdata('cart');
				if(!in_array($id, $cart))
					return TRUE;
				$this->form_validation->set_message(__FUNCTION__, lang('product_was_bought'));
				return FALSE;
			}
			$this->form_validation->set_message(__FUNCTION__, lang('product_exprise'));
			return FALSE;
		}
		$this->form_validation->set_message(__FUNCTION__, lang('invalid_product_id'));
		return FALSE;
	}

	public function _check_capcha($val) {
		if ($val == $this->session->userdata('captcha'))
			return TRUE;
		$this->form_validation->set_message(__FUNCTION__, lang('invalid_captcha'));
		return FALSE;
	}

}

?>
